% display all neuron weights as a 2d array of images
% assumes the weights are square 2d arrays for each neuron
%
% w(pixels,neurons) is the som weight matrix if visualize_rows = false;
%  or
% w(neurons, pixels) if visualize_rows = true;
%
%function visualize_som(w, pixelrows, pixelcols,visualize_rows)

function visualize_som(w,pixelrows,pixelcols,visualize_rows)

if ~exist('visualize_rows')
    visualize_rows = false;
end
    
k=1;

if visualize_rows
    neuronrows = ceil(sqrt(size(w,1)));
    neuroncols = ceil(sqrt(size(w,1)));
    subplots = size(w,1);
else
    neuronrows = ceil(sqrt(size(w,2)));
    neuroncols = ceil(sqrt(size(w,2)));
    subplots = size(w,2);
end

contrast = [min(min(w)) max(max(w))+.000001];

outimage = contrast(2)*ones(neuronrows*(pixelrows+1),neuroncols*(pixelcols+1));
outimagerow=1;
for i = 1:neuronrows
    outimagecol=1;
    for j = 1:neuroncols
        
        if k > subplots 
            break;
        end
        %subplot(neuronrows,neuroncols,k);

        if visualize_rows
            a=reshape( w(k,:), pixelrows, pixelcols );
        else
            a=reshape( w(:,k), pixelrows, pixelcols );
        end
        
        outimage(outimagerow:outimagerow+pixelrows-1,outimagecol:outimagecol+pixelcols-1)...
            = a;
        
        k=k+1;
        outimagecol=outimagecol+pixelcols+1;
    end
    outimagerow=outimagerow+pixelrows+1;
end
imagesc( outimage,contrast);
axis off
colormap(gray);


